package com.tsit.study.netty.client;

import com.tsit.study.netty.handler.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author wangxuzhi
 * @date 2020/11/24 17:01
 */
@Slf4j
@Component
public class NettyClient {

    public static ChannelFuture cf;

    @Value("${netty.server.host}")
    private String host;

    @Value("${netty.server.port}")
    private int port;

    public void start() {
        // 配置客户端
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline()
                                    .addLast(new HttpClientCodec())
                                    .addLast(new NettyClientHandler());
                        }
                    });
            ChannelFuture f = b.connect(host, port).sync();
            cf = f;
            Channel ch = f.channel();
            log.info("建立netty连接成功");

            ch.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {

            // 优雅的关闭
            group.shutdownGracefully();
        }
    }
}
